package com.ethan.lotgateway.netty.handler;

import com.ethan.lotgateway.ChannelInfo;
import com.ethan.lotgateway.DataInfo;
import com.ethan.lotgateway.untils.Comm;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class ChannelManagerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        Comm.CHANNEL_INFO_MAP.put(ctx.channel().id(), new ChannelInfo());
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("收到消息--"+msg);
        DataInfo dataInfo = new DataInfo();
        if (msg instanceof ByteBuf) {
            //1234#23.4#10 //编号，温度，电压
            ByteBuf byteBuf = (ByteBuf) msg;
            String sourceStr = byteBuf.toString(CharsetUtil.UTF_8);
            String sn = sourceStr.split("#")[0];
            dataInfo.setDeviceId(sn);
            dataInfo.setData(sourceStr);
            System.out.println("收到消息--"+sourceStr);
            ctx.fireChannelRead(dataInfo);
        }

    }
}
